<template>
    <div>
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
          <el-button
            type="primary"
            @click="dialogFormVisible = true"
            icon="el-icon-plus"
            v-btnPower="'btn.Trademark.add'"
            >添加</el-button
          >
        </template>
        <el-table
          v-loading="loading"
          style="margin-bottom: 10px"
          border
          :data="trademarkList"
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
          <el-table-column label="品牌LOGO" #default="{ row, $index }">
            <img style="width: 100px" :src="row.logoUrl" alt="" />
          </el-table-column>
          <el-table-column label="操作" #default="{ row, $index }">
            <el-button
              type="warning"
              icon="el-icon-edit-outline"
              size="small"
              @click="editTrademark(row)"
              v-btnPower="'btn.Trademark.update'"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteTrademark(row)"
              v-btnPower="'btn.Trademark.remove'"
              >删除</el-button
            >
          </el-table-column>
        </el-table>
        <el-pagination
          @current-change="setCurrent"
          @size-change="setSize"
          :page-sizes="[3, 6, 9]"
          :page-size="pagesize"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
        >
        </el-pagination>
      </el-card>
      <el-dialog @close="closeBefore" :title="formData.id?'编辑品牌':'添加品牌'" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" ref="formData" :model="formData" label-width="100px">
          <el-form-item  prop="tmName" label="活动名称">
            <el-input
              placeholder="请输入品牌名称"
              size="small"
              style="height: 20px; width: 200px"
              v-model="formData.tmName"
            ></el-input>
          </el-form-item>
          <el-form-item ref="upLoad" prop="logoUrl" label="品牌LOGO">
            <el-upload
              class="avatar-uploader"
              action="http://101.43.227.123:5555/app-prod/admin/product/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formData.logoUrl"
                :src="formData.logoUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <template #tip>
                <div>上传图片必须是jpg且不能大于2M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSave"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import prjectApi from "@/api/project";
  import { Message } from "element-ui";
  export default {
    name: "BackgroundItemsIndex",
    data() {
      var validTrademarkName=(rule, value, callback)=>{
        if(!value){
          return callback(new Error('名称不能为空'));
        }
        if(value.length<5){
          return callback(new Error("品牌需大于4个字"));
        }
        return callback()
      }
      var valiImageUrl=(rule, value, callback)=>{
          if(!this.formData.logoUrl){
            return callback(new Error("请上传文件"));
          }
          return callback()
      }
      return {
        current: 1,
        pagesize: 3,
        trademarkList: [],
        total: 0,
        loading: false,
        // 模态框显示隐藏
        dialogFormVisible: false,
        // 表单上传
        formData: {
          tmName: "",
          logoUrl: "",
        },
        rules: {
          tmName: [{ validator: validTrademarkName, trigger: "blur" }],
          logoUrl: [{ required: true, validator:valiImageUrl, trigger: "change" }],
        },
      };
    },
  
    mounted() {
      this.setTrademark();
    },
    methods: {
      // 获取表格列表
      async setTrademark() {
        try {
          this.loading = true;
          let { data } = await prjectApi.reqTrademark({
            current: this.current,
            pagesize: this.pagesize,
          });
          this.trademarkList = data.records;
          this.current = data.current;
          this.pagesize = data.size;
          this.total = data.total;
        } catch (error) {
        } finally {
          this.loading = false;
        }
      },
      // 删除品牌
      async deleteTrademark(item) {
        try {
          await this.$alert(`确定删除${item.tmName}`, "警告", {
            confirmButtonText: "确定",
            showCancelButton: "取消",
          });
          await prjectApi.reqDelete(item.id);
          Message.success("删除成功");
          this.setTrademark();
        } catch (error) {
          if (error == "cancel") return;
          Message.error(error);
        }
      },
      // 修改当前页
      setCurrent(current) {
        this.current = current;
      },
      setSize(pagesize) {
        this.pagesize = pagesize;
      },
      // 文件上传成功
      handleAvatarSuccess(res, file) {
        console.log(res);
        this.formData.logoUrl = res.data
        this.$refs.upLoad.clearValidate()
      },
      // 文件上传前
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg";
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
      // 保存添加的文件
      onSave(){
        this.$refs.formData.validate((valid) => {
            if (valid) {
             this.reqSaveTrademark()
            } else {
              return false;
            }
          });
  
      },
      // 保存添加的属性
     async reqSaveTrademark(){
        try {
          await prjectApi.saveTrademark(this.formData)
          Message.success("保存成功")
          this.setTrademark()
        } catch (error) {
          Message.error("保存失败")
        }finally{
          this.dialogFormVisible = false
        }
      },
      editTrademark(item){
        this.dialogFormVisible = true
        this.formData={...item}
      },
      // 关闭前
      closeBefore(){
        this.formData={}
      }
    },
    computed: {
      // 监听current和pagesize
      czChange() {
        let { current, pagesize } = this;
        return {
          current,
          pagesize,
        };
      },
    },
    watch: {
      // 监听current和pagesize
      czChange() {
        this.setTrademark();
      },
    },
  };
  </script>
  
  <style scoped>
  .avatar-uploader >>> .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  